<template>
    <div ref="canvas"></div>
</template>

<script setup lang="ts">
import { Chart, View } from '@antv/g2';
import { v4 } from 'uuid';
import { onMounted, onUnmounted, ref, shallowRef, watch } from 'vue';
import moment from 'moment';
type IDate = { type: string, count: number, day: string }
const prop = defineProps<{ data: IDate[], height: number, color?: string[] }>()
const tclass = v4()
const canvas = ref<HTMLDivElement>()
const chart = shallowRef<Chart>()



const _chart = shallowRef<View>()

watch(() => prop.data, () => {
    _chart.value?.changeData(prop.data);
    // chart.value?.theme({ "styleSheet": { "brandColor": "#014c63", paletteQualitative10: prop.color, paletteQualitative20: prop.color } });
    // chart.value?.interval()
    //     .position('count')
    //     .color('name', prop.color)
    //     .label('name')
    //     .adjust('stack');
    _chart.value?.render();
})



onMounted(() => {
    // let all = 0
    // prop.data.forEach((a) => all = a.count + all)
    if (canvas.value) {
        chart.value = new Chart({
            container: canvas.value,
            autoFit: true,
            height: prop.height,
            padding: [70, 80, 70, 80]
        })
        chart.value.data(prop.data);
        chart.value.line().position('day*count').color('type').tooltip('day*count*type', (day, count, type) => {
            const title1 = moment(day, 'YYYY-WW').format('YYYY-WW周')
            const title2 = moment(day, 'YYYY-WW').format('MM-DD')
            const title3 = moment(day, 'YYYY-WW').add(1, 'week').format('MM-DD')
            const data = {
                title: `${title1} (${title2} - ${title3})`,
                value: count,
                name: type
            }

            return data
        })


        _chart.value = chart.value.interaction(tclass);
        chart.value.render();
    }
})

onUnmounted(() => {
    if (_chart.value)
        _chart.value.removeInteraction(tclass)
})

defineExpose({
    data: _chart.value
})

</script>